const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const StylelintPlugin = require('stylelint-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

module.exports = (env) => {
  // css loader
  const cssLoader = [
    env === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
    'css-loader',
    'postcss-loader',
  ]

  // 根据env添加的插件
  const plugins = []
  if (env === 'production') {
    plugins.push(new MiniCssExtractPlugin())
  }

  return {
    mode: 'none',
    entry: './src/main.js',
    module: {
      rules: [
        {
          test: /\.less$/,
          use: [
            ...cssLoader,
            'less-loader',
          ]
        },
        {
          test: /\.css$/,
          use: [
            ...cssLoader,
          ]
        },
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: [
            'babel-loader',
          ]
        },
        {
          test: /\.(png|jpg|jpeg|git)$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 10 * 1024,
              esModule: false,
            }
          }
        },
        {
          test: /\.(js|vue)$/,
          use: [
            'eslint-loader',
          ],
          enforce: 'pre'
        },
        {
          test: /\.vue$/,
          use: [
            // 'thread-loader',
            'vue-loader',
          ]
        }
      ]
    },
    plugins: [
      ...plugins,
      new VueLoaderPlugin(),
      new StylelintPlugin({
        files: ['src/**.{vue,html,css,less}'],
        fix: false,
        cache: false,
        emitError: true,
        failOnError: false,
      }),
      new HtmlWebpackPlugin({
        template: './public/index.html',
        title: '作业'
      }),
      new webpack.DefinePlugin({
        BASE_URL: '"./"'
      }),
      new FriendlyErrorsPlugin(),
    ],
    resolve: {
      extensions: ['.js', '.json', '.vue']
    }
  }
}